let secret_code = ''
//获取应用实例
const app = getApp()
Page({
  data: {
    mobile:'',
    countDownVisible: false,
    code:'',
    redirect:''

  },

  onLoad({redirectURL}){
    //获取地址参数
    this.setData({redirectURL})
  },

  countDownChange(ev) {
    this.setData({
      timeData: ev.detail,
      countDownVisible: ev.detail.minutes === 1 || ev.detail.seconds > 0,
    })
  },
  verifyMobile(){
   const reg =/^(?:(?:\+|00)86)?1(?:(?:3[\d])|(?:4[5-79])|(?:5[0-35-9])|(?:6[5-7])|(?:7[0-8])|(?:8[\d])|(?:9[1589]))\d{8}$/
   const valid = reg.test(this.data.mobile.trim())
   if(!valid) wx.utils.toast("请填写正确的手机号码")
   return valid
  },
  verifyCode(){
    const reg =/^\d{6}$/
    //验证验证码
    const valid =reg.test(this.data.code.trim())
    if(!valid) wx.utils.toast('请检查验证码是否正确！')
    //返回验证结果
    return valid
  },
  async getCode(){
    if(!this.verifyMobile()) return
   const {code,data}=await wx.http.get('/code',{mobile:this.data.mobile.trim()})
  //  console.log(res)
    if(code!==10000) return wx.utils.toast('发送失败，请稍后重试')
    wx.utils.toast('发送成功，请查收短信')
    this.setData({countDownVisible:true})
    secret_code=data.code
  },
  //复制验证码
  copyCode(){
    wx.setClipboardData({
      data:secret_code
    })
  },
  // async submitForm(){
  //   //逐个验证表单数据
  //   if(!this.verifyMobile()) return
  //   if(!this.verifyCode()) return

  //   const {mobile,code} =this.data
  //   const res =await wx.http.post('/login',{mobile,code})
  //   if(res.code!==10000) return wx.utils.toast('请检查验证码是否正确！')
  //   app.setToken(res.data.token,res.data.refreshToken)
  //   //重定向至登录前的页面
  //     wx.reLaunch({
  //       url: '/',
  //     })
  // },
  async onLogin(){
   if(!this.verifyMobile()) return
   if(!this.verifyCode()) return
   const res = await wx.http.post('/login',{mobile:this.data.mobile,code:this.data.code})
   wx.utils.toast('登录成功')
   wx.setStorageSync('token', res.data.token)
   getApp().token=res.data.token
   const redirect=this.data.redirect||'pages/my/index'
   wx.reLaunch({
     url: '/' + redirect
   })
  }
})
